package com.sishuok.estest.springclient;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;

@Service
public class GeoSpringClient {
	@Autowired
	private ElasticsearchTemplate et;
	@Autowired
	ElasticsearchOperations operations;
	public final static String INDEX_NAME = "mytest4";
	public final static String PRODUCT_DOCUMENT_TYPE = "geoType1";

	public List<Object> findByGeoLocation(Double longitude, Double latitude, String index, String distance) {

		if (StringUtils.isEmpty(distance)) {
			distance = "5000km";
		}
		GeoPoint location = new GeoPoint(latitude, longitude);
		CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("location").within(location, distance));
		criteriaQuery.addIndices(index);
		criteriaQuery.addTypes(PRODUCT_DOCUMENT_TYPE);
		criteriaQuery.addSort(new Sort(Sort.Direction.ASC, "name"));
		
		List<Object> sites = et.queryForList(criteriaQuery, Object.class);
		return sites;
	}

	public void geoSpatialSearch() {

		GeoPoint startLocation = new GeoPoint(39.13D, 117.20D);
		String range = "530km"; // or 530km
		CriteriaQuery query = new CriteriaQuery(new Criteria("location").within(startLocation, range));
		List<Position> queryForList = operations.queryForList(query, Position.class) ;
		System.out.println(queryForList);
		
	}

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-es.xml");
		GeoSpringClient mt = (GeoSpringClient) ctx.getBean("geoSpringClient");
		List<Object> findByGeoLocation = mt.findByGeoLocation(117.20, 39.13, INDEX_NAME, "50");
		System.out.println(JSON.toJSON(findByGeoLocation));

		mt.geoSpatialSearch();
	}
}
